<template>
  <div>
    <div class="container mt-4  px-4 mt-9">
      <div class="header color-default">
        <div class="title">{{examType == '0' ? '模拟' : ''}}考试</div>
        <div class="time img">
          <span><img :src="img.time" alt="计时"></span>
          <span class="text pl-2">{{usedTime}}/{{allTime}}</span>
        </div>
      </div>
      <div class="subject">
        <div class="content">
          {{questionNo}}. {{questionInfo.content}}
        </div>
        <div class="item no-mint-style">
          <mt-radio class="selection-list" :options="questionInfo.items" v-model="questionList[questionNo-1].answer"></mt-radio>
        </div>
      </div>

    </div>

    <div class="exam-tip">

      <div class="button-group">
        <div class="x-row pb-9">
          <div class="x-col-6 pr-4">
            <mt-button type="primary" :disabled="!prevEnabled" :class="{'bg-light-gray': !prevEnabled, 'bg-light-blue': prevEnabled}" @click="prev">上一题</mt-button>
          </div>
          <div class="x-col-6 pl-4">
            <mt-button type="primary" :disabled="!nextEnabled" :class="{'bg-light-gray': !nextEnabled, 'bg-light-blue': nextEnabled}" @click="next">下一题</mt-button>
          </div>
        </div>
      </div>

      <div class="x-row bordered pt-4">
        <div class="x-col-6 text-left img">
          <span><img :src="img.progress"></span>
          <span class="text">{{questionNo}}/{{questionCount}}</span>
        </div>
        <div class="x-col-6 text-right img">
          <span><img :src="img.submit"></span>
          <span class="text" @click="checkPersonIdentityBeforeSubmit()">交卷</span>
        </div>
      </div>
    </div>
    <div>
      <form action="javascript:;" ref="photoFileForm">
        <input ref="photoFile" type="file" v-show="false" @change="handlePhotoFileChange" accept="image/*" capture="camera" />
      </form>
    </div>
  </div>
</template>


<script>

import timeImg from '@/assets/images/exam/考试_计时.png'
import progressImg from '@/assets/images/exam/考试_左下.png'
import submitImg from '@/assets/images/exam/考试_交卷.png'

import examApi from '@/api/exam'
import { Toast } from 'mint-ui'
import { MessageBox } from 'mint-ui'
import { Const } from '@/consts'
import utils from '@/utils'

export default {
  data () {
    return {
      // 用于存储正在进行验证的状态
      checking: false,
      empty: false,
      // 身份验证类型,0:考试中验证,1:交卷验证
      personIdentityCheckType: '0',
      personIdentityCheckTime: 0,
      checkPersonTimePoint: '',
      // 考试时间结束
      isTimeout: false,
      // 存在未答题
      isForce: false,
      img: {
        time: timeImg,
        progress: progressImg,
        submit: submitImg
      },
      examInfo: {
      },
      questionInfo: {
        items: []
      },
      questionList: [{
        answer: ''
      }],
      questionNo: 1,
      questionCount: 1,
      usedTimeInterval: 0,
      usedTime: '00:00:00',
      allTimeInterval: 0,
      allTime: '00:00:00',
      prevEnabled: false,
      nextEnabled: false,
      examType: '0',
      intervalId: '',
      courseId: '',

      buttonEnabled: {
        submit: true
      }
    }
  },

  created () {
    this.getQueryParams();
    this.getExamInfo();
    this.getQuestionList();
  },

  methods: {

    getQueryParams () {
      const courseId = this.$route.query && this.$route.query.courseId || '';
      const examType = this.$route.query && this.$route.query.examType || '';

      if (!courseId) {
        Toast('出错了 ...');
        return;
      }

      this.examType = examType;
      this.courseId = courseId;
    },

    getExamInfo () {
      const courseId = this.courseId;

      if (!courseId) {
        return;
      }

      examApi.getExamInfo({
        params: {
          courseid: courseId
        }
      }).then((resp) => {
        this.examInfo = resp[Const.RESP_RESULT] || {};
        this.allTimeInterval = (this.examInfo.duration || 0) * 60;
        // 即将结束的时候进行身份验证不合适,进度达到20%-40%的时候,随机进行人脸识别
        this.checkPersonTimePoint = Math.round(this.allTimeInterval * 0.2 + Math.random() * this.allTimeInterval * 0.2)
        this.allTime = utils.secondsToDateString(this.allTimeInterval);

        if (this.examType == '1' && this.examInfo.retrytime > 3) {
          this.examType = '0';
        }


      }).catch((resp) => {
        // Toast(resp[Const.RESP_MESSAGE] || '获取考试信息失败');
        if (resp.statusCode == '200') {
          Toast(resp[Const.RESP_MESSAGE] || '获取信息失败');
        }
      });
    },

    getQuestionList () {
      const courseId = this.courseId;

      if (!courseId) {
        return;
      }

      // examApi.getQuestionList({
      examApi.startExam({
        params: {
          courseid: courseId,
          examtype: this.examType == '1' ? 'REAL' : 'SIMULATION'
        }
      }).then((resp) => {
        const result = resp[Const.RESP_RESULT] || [];
        let questionList = [];

        for (let i = 0; i < result.length; i++) {
          let items = [];
          let r = result[i];

          if (r.optiona) {
            items.push({
              value: '1',
              label: r.optiona
            });
          }

          if (r.optionb) {
            items.push({
              value: '2',
              label: r.optionb
            });
          }

          if (r.optionc) {
            items.push({
              value: '3',
              label: r.optionc
            });
          }

          if (r.optiond) {
            items.push({
              value: '4',
              label: r.optiond
            });
          }

          questionList.push({
            index: i,
            questionid: r.questionid,
            content: r.content,
            questiontype: r.questiontype,
            items: items
          });
        }

        this.questionList = questionList;
        this.start();
        this.questionCount = this.questionList.length;

        if (this.questionCount > 1) {
          this.nextEnabled = true;
        }

      }).catch((resp) => {
        // Toast(resp[Const.RESP_MESSAGE] || '获取试题信息失败');
        if (resp.statusCode == '200') {
          Toast(resp[Const.RESP_MESSAGE] || '获取信息失败');
          this.$router.go(-1)
        }
      });
    },

    start () {
      this.questionInfo = this.questionList[this.questionNo - 1];
      this.intervalId = setInterval(() => {
        if (this.usedTimeInterval >= this.allTimeInterval) {
          clearInterval(this.intervalId);
          this.intervalId = '';
          this.isTimeout = true
          this.checkPersonIdentityBeforeSubmit();
          return;
        } else {
          this.usedTime = utils.secondsToDateString(++this.usedTimeInterval);
        }
        if (this.$route.query && this.$route.query.examType == '1') {
          if (this.usedTimeInterval == this.checkPersonTimePoint) {
            // 考试中验证
            if (!this.checking) {
              this.personIdentityCheckType = '0'
            }
            this.checkPersonIdentity()
          }
        }
        if (this.usedTimeInterval >= this.allTimeInterval) {
          clearInterval(this.intervalId);
          this.intervalId = '';
          this.isTimeout = true;
          this.checkPersonIdentityBeforeSubmit();
        }
      }, 1000);
    },

    prev () {

      if (this.questionNo > 1) {
        this.questionNo = this.questionNo - 1;
        this.questionInfo = this.questionList[this.questionNo - 1];
      }

      if (this.questionNo == this.questionCount) {
        this.nextEnabled = false;
      } else {
        this.nextEnabled = true;
      }

      if (this.questionNo == 1) {
        this.prevEnabled = false;
      } else {
        this.prevEnabled = true;
      }
    },

    next () {
      if (this.questionNo < this.questionCount) {
        this.questionNo = this.questionNo + 1;
        this.questionInfo = this.questionList[this.questionNo - 1];
      }

      if (this.questionNo == this.questionCount) {
        this.nextEnabled = false;
      } else {
        this.nextEnabled = true;
      }

      if (this.questionNo == 1) {
        this.prevEnabled = false;
      } else {
        this.prevEnabled = true;
      }
    },

    doSubmit (answer) {

      const answerMap = this.empty ? this.makeEmpty(answer) : answer
      examApi.submit({
        params: {
          courseid: this.courseId,
          examtype: this.examType == '0' ? 'SIMULATION' : 'REAL',
          //answermap: this.empty ? JSON.stringify(this.makeEmpty(answer)) : JSON.stringify(answer)
          answermap: JSON.stringify(answerMap)
        }
      }).then((resp) => {

        let result = resp[Const.RESP_RESULT] || {};
        let wrongList = result.wronglist || [];
        let examResult = {};

        examResult.examId = result.examid;
        examResult.retrytime = result.retrytime || 0;
        examResult.score = result.score || 0;
        examResult.duration = result.duration || Math.ceil(this.usedTimeInterval / 60);
        examResult.usedTime = this.usedTimeInterval;
        examResult.count = this.questionCount;
        examResult.wrong = wrongList.length;
        examResult.right = this.questionCount - examResult.wrong;
        examResult.answerMap = answerMap;
        examResult.wrongList = wrongList;
        utils.save('EXAM-' + examResult.examId, examResult);

        this.$router.replace({
          path: '/exam/point',
          query: {
            courseId: this.courseId,
            examType: this.examType,
            examId: examResult.examId
          }
        });

        Toast(result.pass === true ? '考试通过' : '考试未通过')

      }).catch((resp) => {
        // Toast('交卷失败了，请重试');
        this.buttonEnabled.submit = true;
        if (resp.statusCode == '200') {
          Toast(resp[Const.RESP_MESSAGE] || '交卷失败了，请重试');
        } else {
          Toast('交卷失败了，请重试');
        }
      });
    },
    // 清空答案
    makeEmpty (answer) {
      for (let i in answer) {
        console.log(answer[i])
        answer[i] = ''
      }
      return answer
    },
    checkPersonIdentity () {
      if (this.checking) {
        return
      } else {
        this.checking = true
      }
      if (this.personIdentityCheckTime >= 3) {
        this.empty = true
        this.isForce = true
        setTimeout(this.submit(this.isForce), 3000)
      } else {
        MessageBox({
          message: this.personIdentityCheckType == '1' ? '交卷前需要进行身份验证' : '根据考试规定，需要再次进行身份验证',
          confirmButtonText: '验证',
          showCancelButton: false,
          closeOnClickModal: false
        }).then(resp => {
          this.personIdentityCheckTime++
          this.$refs.photoFile.click()
        })
      }
    },
    handlePhotoFileChange () {
      const file = this.$refs.photoFile.files[0]

      if (!file) {
        return;
      }

      this.$refs.photoFileForm.reset();

      examApi.compareFace({
        params: {
          courseid: this.courseId,
          facepic: file
        }
      }).then(resp => {
        if (resp[Const.RESP_RESULT] === true) {
          this.personIdentityCheckTime = 0
          if (this.personIdentityCheckType == '0') {
            this.checking = false
            Toast('验证通过,继续考试...')
          } else if (this.personIdentityCheckType == '1') {
            this.submit(this.isForce)
          }
        } else {
          MessageBox.alert('验证失败,三次验证失败之后将直接交白卷').then(resp => {
            this.checking = false
            this.checkPersonIdentity()
          })
        }
      }).catch(resp => {
        MessageBox.alert('验证失败,三次验证失败之后将直接交白卷').then(resp => {
          this.checking = false
          this.checkPersonIdentity()
        })
      })

    },
    // 交卷之前调用这个方法
    checkPersonIdentityBeforeSubmit () {
      // 考试结束验证
      if (this.isTimeout) {
        Toast('已到结束时间，自动交卷中 ...');
        this.isForce = true
      } else {
        this.isForce = false
      }
      this.checkAnswerAllQuestion()
    },
    // 检测是否已经全部答题完毕
    checkAnswerAllQuestion () {
      let answer = {}
      let q
      let answerNoList = []
      for (let i = 0; i < this.questionList.length; i++) {
        q = this.questionList[i]
        if (q.answer != null) {
          answer[q.questionid] = q.answer - 0
          answerNoList.push(q.questionid)
        }
      }
      if (this.isForce) {
        this.checking = false
        this.submit(this.isForce)
      } else if (answerNoList.length < this.questionList.length) {
        MessageBox.confirm('您还有未答的题目，确定要交卷么？', '温馨提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          closeOnClickModal: false,
          type: 'info'
        }).then(action => {
          if (this.examType == '1') {
            this.personIdentityCheckType = '1'
            this.personIdentityCheckTime = 0
            this.checking = false
            this.checkPersonIdentity()
          } else {
            this.submit(this.isForce)
          }
        }).catch(() => {
          this.buttonEnabled.submit = true;
        });
      } else {
        if (this.examType == '1') {
          this.personIdentityCheckType = '1'
          this.personIdentityCheckTime = 0
          this.checking = false
          this.checkPersonIdentity()
        } else {
          this.submit(this.isForce)
        }
      }
    },
    submit (isForce) {
      clearInterval(this.intervalId)
      let answer = {}, q, answerNoList = [];
      for (let i = 0; i < this.questionList.length; i++) {
        q = this.questionList[i];
        if (q.answer != null) {
          answer[q.questionid] = q.answer - 0;
          answerNoList.push(q.questionid);
        }
      }

      let courseId = this.courseId;

      if (!courseId) {
        Toast('出错了...');
        return;
      }

      if (this.buttonEnabled.submit) {
        this.buttonEnabled.submit = false;
      } else {
        return;
      }
      this.doSubmit(answer)
    }
  }
}
</script>

<style lang="scss" scoped>
$scale: 1.2;
$content-font-size: 24px;

.container {
  margin-bottom: 200px;
}

.header {
  border-bottom: 1px solid #dddddd;
  .title {
    font-size: $content-font-size * $scale;
    padding-top: 36px;
  }

  .time {
    padding: $content-font-size 0;
    font-size: 16px * $scale;
  }
}

.subject {
  text-align: left;
  word-break: break-all;
  font-size: 16px * $scale;
  .content {
    padding: 24px 0 10px 0;
    line-height: 20px;
  }

  .item {
    line-height: 16px;
  }
}

.img {
  img {
    width: $content-font-size;
    vertical-align: middle;
  }
  .text {
    vertical-align: middle;
    padding-left: 8px;
  }
}

.button-group {
  .mint-button {
    width: 100%;
  }
  margin-bottom: 20px;
}

.exam-tip {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 0 20px 24px 20px;
  box-sizing: border-box;
  background: #ffffff;
  font-size: 16px * $scale;
  .bordered {
    border-top: 1px solid #e7e7e7;
  }
}
</style>
